package com.haidechizi.i18n.code.generator.common.message.generator;

import com.google.common.collect.Lists;
import com.haidechizi.i18n.code.generator.common.GlobalConfig;
import com.haidechizi.i18n.code.generator.common.message.config.GeneratorProperties;
import com.haidechizi.i18n.code.generator.common.message.file.FilePathResolverProxy;
import com.haidechizi.i18n.code.generator.common.message.global.GlobalParam;
import com.haidechizi.i18n.code.generator.common.message.holder.GeneratorHolder;
import com.haidechizi.i18n.code.generator.common.message.param.Param;
import com.haidechizi.i18n.code.generator.common.message.reader.Reader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Generators {

    @Autowired
    private GeneratorProperties generatorProperties;

    @Autowired
    private Reader reader;

    @Autowired
    private FilePathResolverProxy filePathResolverProxy;

    public String generator(Param param) {
        // 校验参数
        GlobalParam.setParam(param);
        GlobalConfig.setTranslateType(param.getTranslateType());
        CodeGenerator codeGenerator = GeneratorHolder.getInstance(param.getType());

        String resolverPath = filePathResolverProxy.resolverPath(param.getFilePath());
        param.setBasePath(resolverPath);

        List<String> paths = createPaths(param);
        paths.forEach(codeGenerator::generator);
        // 创建资源文件
        if (GlobalParam.getParam().isGeneratePropertiesFile()) {
            codeGenerator.createPropertiesFile(paths.get(0));
        }
        return null;
    }

    private List<String> createPaths(Param param) {
        List<String> paths = new ArrayList<>();
        if (CollectionUtils.isEmpty(param.getSubPaths())) {
            paths = Lists.newArrayList(param.getBasePath());
        }
        if (!CollectionUtils.isEmpty(param.getSubPaths())) {
            paths = param.getSubPaths().stream().map(subPath -> {
                return param.getBasePath() + File.separator + subPath;
            }).collect(Collectors.toList());
        }
        // 获取具体文件的路径
        List<String> filePaths = new ArrayList<>();
        paths.forEach(path -> {
            filePaths.addAll(reader.loadFiles(path));
        });
        return filePaths;
    }
}
